package com.wsd.serviceImpl;


import com.wsd.common.Result;
import com.wsd.common.TypeSwitch;
import com.wsd.constant.ResultCode;
import com.wsd.dao.LoanInformationMapper;
import com.wsd.dao.LoanLimitMapper;
import com.wsd.dao.RepaymentPlanMapper;
import com.wsd.dao.RepaymentRecordMapper;
import com.wsd.domain.*;
import com.wsd.service.RepaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;

/**
 * @author Wang Yu
 * @date 2020/7/19-15:18
 */
@Service

public class RepaymentServiceImpl implements  RepaymentService
{

    @Autowired
    private LoanInformationMapper loanInformationMapper;
    @Autowired
    private RepaymentPlanMapper repaymentPlanMapper;
    @Autowired
    private RepaymentRecordMapper repaymentRecordMapper;
    @Autowired
    private LoanServiceImpl loanService;
    @Autowired
    private TypeSwitch typeSwitch;
    @Autowired
    private LoanLimitMapper loanLimitMapper;


    @Override
    public Result PlanRepayment(RepaymentInfomation repaymentInfomation) {

        BigDecimal repayAmount = repaymentInfomation.getRepaymentAmount();
        //根据分期编号查询还款计划金额
        long planId = repaymentInfomation.getPlanId();
        long loanId = repaymentInfomation.getLoanId();
        RepaymentPlan repaymentPlan = repaymentPlanMapper.selectByPrimaryKey(planId);
        LoanInformation loanInformation = loanInformationMapper.selectByPrimaryKey(loanId);
        //获取本期金额
        BigDecimal repayableAmount =  repaymentPlan.getRepayableAmount();

        //查询客户号
        Long customerId = loanInformation.getCustomerId();

        if(repayableAmount.compareTo(repayAmount)!=0)
        {
            //还款金额与可还金额不想等，返回错误

            return new Result(ResultCode.PARAM_IS_INVALID.getCode(),"还款金额不足",repayableAmount);//返回错误码
        }

        //更新贷款信息表
        BigDecimal RemainPrincipal = loanInformation.getRemainPrincipal();
        RemainPrincipal = RemainPrincipal.subtract(repaymentPlan.getPrincipalPart());
        loanInformation.setRemainPrincipal(RemainPrincipal);
        if(loanInformation.getRemainPrincipal().equals(BigDecimal.ZERO))
        {
            loanInformation.setLoanStatus("2"); //本金还完，status设置为2完结
        }
        loanInformationMapper.updateByPrimaryKeySelective(loanInformation); //更新贷款信息表




        //额度恢复
        LoanLimit loanLimit = loanLimitMapper.selectByCustomerId(customerId);
        BigDecimal avalible = loanLimit.getAvailableLimit().add(repaymentPlan.getPrincipalPart()); //本金部分恢复至额度
        loanLimit.setAvailableLimit(avalible);
        loanLimit.setUsedLimit(loanLimit.getUsedLimit().subtract(repaymentPlan.getPrincipalPart()));
        loanLimitMapper.updateByPrimaryKeySelective(loanLimit);

        //核销还款计划
        repaymentPlan.setRepayableAmount(new BigDecimal("0"));
        repaymentPlan.setInterestPart(new BigDecimal("0"));
        repaymentPlan.setPrincipalPart(new BigDecimal("0"));
        repaymentPlan.setOverdueInterest(new BigDecimal("0")); //逾期利息清零
        repaymentPlan.setRepaymentStatus("1");//还款状态
        repaymentPlanMapper.updateByPrimaryKeySelective(repaymentPlan);


        return new Result(ResultCode.SUCCESS.getCode(),"还款成功",repaymentPlan); //返回成功状态
    }

    @Override
    public Result PreRepayment(RepaymentInfomation repaymentInfomation) {
        Long loanId = repaymentInfomation.getLoanId();

        //查询当前贷款编号对应的所有还款计划
        List<RepaymentPlan> repaymentPlanList = repaymentPlanMapper.selectRepaymentPlanByLoanId(loanId);
        //查询当前贷款剩余本金
        LoanInformation loanInformation = loanInformationMapper.selectByPrimaryKey(loanId);
        //查询当前贷款编号对应贷款日期
        LocalDateTime loanStratTime = loanInformation.getLoanStartTime();
        //查询用户id
        Long customerId = loanInformation.getCustomerId();


        BigDecimal remainPrincipal = loanInformation.getRemainPrincipal();

        //更新贷款计划表
        BigDecimal newRemainPrincipal = remainPrincipal.subtract(repaymentInfomation.getRepaymentAmount());
        loanInformation.setRemainPrincipal(newRemainPrincipal);

        //本金还完，status设置为2完结
        if(newRemainPrincipal.compareTo(BigDecimal.ZERO)==0)
        {
            //贷款信息表结清
            loanInformation.setLoanStatus("2");
        }
        loanInformationMapper.updateByPrimaryKeySelective(loanInformation);


        //额度恢复
        LoanLimit loanLimit = loanLimitMapper.selectByCustomerId(customerId);
        BigDecimal avalible = loanLimit.getAvailableLimit().add(repaymentInfomation.getRepaymentAmount());
        loanLimit.setAvailableLimit(avalible);
        loanLimit.setUsedLimit(loanLimit.getUsedLimit().subtract(repaymentInfomation.getRepaymentAmount()));
        loanLimitMapper.updateByPrimaryKeySelective(loanLimit);

        //将原有未还款的还款计划作废
        int beginIdx = 32; //剩余计划起始期数编号,默认为最大值32
        int remainNum = 0;
        for(RepaymentPlan repaymentPlan:repaymentPlanList)
        {
            if(repaymentPlan.getRepaymentStatus().equals("0")) //还款计划为未结清，作废后重新生成
            {
                //对已还清的还款计划核销
                if(newRemainPrincipal.compareTo(BigDecimal.ZERO)==0)
                {
                    //核销还款计划
                    repaymentPlan.setRepayableAmount(new BigDecimal("0"));
                    repaymentPlan.setInterestPart(new BigDecimal("0"));
                    repaymentPlan.setPrincipalPart(new BigDecimal("0"));
                    repaymentPlan.setOverdueInterest(new BigDecimal("0")); //逾期利息清零
                    repaymentPlan.setRepaymentStatus("1");//还款状态
                    repaymentPlanMapper.updateByPrimaryKeySelective(repaymentPlan);
                    continue;
                }


                //保存未结清还款计划中最小的idx
                beginIdx = repaymentPlan.getInstallmentIdx() < beginIdx ? repaymentPlan.getInstallmentIdx() : beginIdx;
                repaymentPlan.setRepaymentStatus("3");//还款计划作废
                repaymentPlanMapper.updateByPrimaryKeySelective(repaymentPlan);
                remainNum = remainNum + 1;
            }


        }

        //生成新的还款计划并插入表中，贷款编号保持一致
        Loan loan = new Loan();
        loan.setInstallmentNum(remainNum);
        //将作废前一期还款计划的还款时间，作为新的贷款开始时间
        loan.setLoanDate(loanStratTime.plusMonths(beginIdx-1));
        loan.setLoanAmount(newRemainPrincipal);
        loan.setRepaymentType(loanInformation.getRepaymentType().charAt(0)); //RepaymentType类型暂时不一致

        List<RepayPlan> repayPlans = loanService.loanRepayment(loan);

        //将新生成的还款计划插入还款计划表
        for(RepayPlan repayPlan : repayPlans)
        {
            //调整还款计划idx，与之前作废掉的还款计划保持一致
            repayPlan.setInstallmentIdx(beginIdx);
            RepaymentPlan repaymentPlan = typeSwitch.repayPlanToRepaymentPlan(repayPlan);
            repaymentPlan.setLoanId(loanId);
            repaymentPlanMapper.insert(repaymentPlan);
            beginIdx++;
        }


        return new Result(ResultCode.SUCCESS.getCode(),"还款成功",repayPlans); //返回成功状态
    }

}



